<template>
  <a-modal
      title="注册表策略"
      v-model:visible="visible"
      :confirm-loading="confirmLoading"
      :afterClose="remove"
      :bodyStyle="{maxHeight: '1024px', overflow: 'auto'}"
      :width="720"
      @ok="handleOk"
  >
    <a-form :wrapper-col="{span:22,offset:1}">
      <a-form-item>
        <a-textarea
            v-model:value="registry"
            :loading="fileLoading"
            placeholder="注册表路径，每条记录间使用';'分隔"
            :rows="20"
            showCount
            @change="hasChange"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts">
import {defineComponent, reactive, toRefs} from "vue"
import {Modal,Form,Input,message} from "ant-design-vue"
import {GetRegistryValue,UpdateRegistry} from "@/api/strategy/registry"

export default defineComponent({
  name: "RegistryModal",
  props:{
    remove: { // 移除模态框
      type: Function
    },
    fields: {
      type: Object,
      default: () => ({})
    },
    callback: {
      type: Function,
      default: () => ({})
    },
    clientHash:String
  },
  components:{
    [Modal.name]: Modal,
    [Form.name]: Form,
    [Form.Item.name]: Form.Item,
    [Input.TextArea.name]: Input.TextArea,
  },
  setup(props){
    const state=reactive({
      registry:"",
      confirmLoading:false,
      fileLoading:false,
      visible:true,
      changed:false,
    })

    ~async function (){
      state.confirmLoading=true
      state.fileLoading=true
      const blob=await GetRegistryValue({clienthash:props.clientHash})
      const fileReader = new FileReader()
      fileReader.onload=(reader)=>{
        const result: string|any=reader.target?.result??"{}"
        const json=JSON.parse(result)
        state.registry=json.data
        state.fileLoading=false
        state.confirmLoading=false
      }
      fileReader.readAsText(blob,"utf8")
    }()

    const handleOk= async ()=>{
      if(state.changed) {
        state.confirmLoading = true
        const params = {
          hashid: props.clientHash
        }
        const blob = new Blob([state.registry])
        await UpdateRegistry(params, blob).then(res => {
          if (0 == res.code) {
            message.success("设置成功")
          } else {
            message.error(res.data)
          }
        })
        state.confirmLoading = false
      }
      state.visible=false
    }

    const hasChange=()=>{
      state.changed=true
    }

    return {
      ...toRefs(state),
      handleOk,
      hasChange
    }
  }
})
</script>

<style scoped>

</style>
